<!--
 * @Author: 曹捷
 * @Date: 2019-09-10 15:47:03
 * @LastEditors: 曹捷
 * @LastEditTime: 2020-09-16 21:07:33
 * @Description: 时间顶部选择  上一天  下一天
 -->
<template>
  <div class="flex-l-r dateTitle">
    <span @click="monthStep(-1)" class="obit-btn-empty obit-btn">{{ stepBefore }}</span>
    <picker :end="endDate" :fields="type" :start="startDate" :value="date" @change="bindDateChange" mode="date">
      <view class="uni-input">
        <span class="iconfont icon-rili p-r-5"></span>
        {{ date | dateFormat(fmt, tofmt) }}
      </view>
    </picker>
    <span :class="{ 'obit-btn-disabled': maxDate }" @click="monthStep(1)" class="obit-btn-empty obit-btn">{{ stepAfter }}</span>
  </div>
</template>

<script>
import moment from 'moment'

export default {
  props: {
    value: {
      type: String,
    },
    type: {
      type: String,
      default: 'month',
    },
  },
  data() {
    return {
      stepBefore: this.type === 'month' ? '上一月' : '前一天',
      stepAfter: this.type === 'month' ? '下一月' : '后一天',
      fmt: '',
      tofmt: '',
      date: '',
      startDate: '',
      endDate: '',
    }
  },
  watch: {
    date(value) {
      this.$emit('input', value)
      this.$emit('change', this.date)
    },
    value() {
      this.date = this.value
    },
  },
  computed: {
    maxDate() {
      let end = moment(this.endDate, this.fmt)
      let now = moment(this.date, this.fmt)
      let time = now.valueOf() - end.valueOf()
      return time >= 0
    },
  },
  mounted() {
    this.fmt = this.type === 'month' ? 'YYYY-MM' : 'YYYY-MM-DD'
    this.tofmt = this.type === 'month' ? 'YYYY年MM月' : 'YYYY年MM月DD日'
    this.endDate = this.getDate()
    this.startDate = this.getDate('start')
    this.date = this.value || this.getDate()
    console.log('TCL: mounted -> this.date', this.date)
  },
  methods: {
    monthStep(step) {
      if (this.maxDate && step > 0) {
        return
      }
      let m = moment(this.date, this.fmt)
      let type = this.type === 'month' ? 'M' : 'd'
      m.add(step, type)
      let bts = m.valueOf() - moment(this.endDate, this.fmt).valueOf()
      if (bts <= 0) {
        this.date = m.format(this.fmt)
      }
    },
    bindDateChange: function(e) {
      this.date = e.target.value
    },
    getDate(type) {
      let m = moment(new Date())
      if (type === 'start') {
        m.subtract(100, 'Y')
      }
      return m.format(this.fmt)
    },
  },
}
</script>

<style lang="scss">
.dateTitle {
  height: 100rpx;
  background: #fff;
}
</style>
